package com.aitou.mrylive.presentation.ui.room.publish;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.hardware.camera2.CameraCaptureSession;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.jakewharton.rxbinding.view.RxView;
import com.pili.pldroid.player.PLMediaPlayer;
import com.pili.pldroid.streaming.CameraStreamingManager;
import com.pili.pldroid.streaming.CameraStreamingSetting;
import com.pili.pldroid.streaming.StreamStatusCallback;
import com.pili.pldroid.streaming.StreamingProfile;
import com.pili.pldroid.streaming.WatermarkSetting;
import com.pili.pldroid.streaming.widget.AspectFrameLayout;
import com.aitou.mrylive.BeautyLiveApplication;
import com.aitou.mrylive.R;
import com.aitou.mrylive.data.bean.GetFriendBean;
import com.aitou.mrylive.data.bean.me.UserInfo;
import com.aitou.mrylive.data.repository.SourceFactory;
import com.aitou.mrylive.domain.LocalDataManager;
import com.aitou.mrylive.presentation.ui.base.BaseActivity;
import com.aitou.mrylive.presentation.ui.main.currency.CurrencyActivity;
import com.aitou.mrylive.presentation.ui.room.RoomActivity;
import com.aitou.mrylive.presentation.ui.room.RoomFragment;
import com.aitou.mrylive.presentation.ui.room.create.CreateRoomActivity;
import com.aitou.mrylive.presentation.ui.widget.getfriendview.GetFriendLayout;
import com.aitou.mrylive.util.Const;
import com.aitou.mrylive.util.L;
import com.aitou.mrylive.util.TimingLogger;
import com.umeng.analytics.MobclickAgent;
import com.yolanda.nohttp.Headers;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * @author Muyangmin
 * @since 1.0.0
 * 开直播
 */
public class PublishFragment extends RoomFragment implements PublishFragmentUiInterface,
        CameraStreamingManager.StreamingStateListener{

    private static final String ARG_PUSH_ADDRESS = "addr";

    private static final String PLSTREAMERRORSENDFAILED = "PLStreamErrorSendFailed";
    private static final String PLSTREAMERRORRTMPCONNECTSTREAMFAILED = "PLStreamErrorRTMPConnectStreamFailed";
    private PopupWindow popupWindowCamera;
    private String myPlayPath;

    private boolean isStart = false;
    private int PAGER_JSON;
    private View mRoomOwner; //房间主人控件
    public String user_id =null;
    public String user_token=null;
    //倒计时文本
    private TextView tvPublishCountDown;
    private Subscription countdownSubscription;

    //是否可以反转摄像头，通常是由于用户缺少摄像头或被占用造成的。
    private boolean canReverseCamera = true;

    //记录闪光灯是否开启，在切换和退出相机的时候应该关闭闪光灯。
    private Switcher mSwitcher = new Switcher();
    private boolean mIsTorchOn = false;

//    记录是否开启美颜
    private boolean mBeautiful=true;
    protected boolean mIsReady = false;
//   只一次倒计时
    private int Countdown=1;

    protected static final int MSG_START_STREAMING = 0;
    protected static final int MSG_STOP_STREAMING = 1;
    protected static final int MSG_STOP_STREAMING_BAD = 2;

//    推流失败提示
    protected static final int PUBLISH_BAD=3;
//    用来记录是否在 生命周期里面对流进行重启和暂停操作 设置一个全局变量
    public static boolean isCameraManagerPause=true;
//  切换横竖屏推流
    private boolean mOrientationChanged = false;
//    是否是竖屏
    private boolean isEncOrientationPort = true;
//    七牛的推流文件配置
    private StreamingProfile profile;
//    横竖屏管理类
    private EncodingOrientationSwitcher mEncodingOrientationSwitcher = new EncodingOrientationSwitcher();
//    是否是切换横竖屏推流
    private boolean isOren=false;
    //    自定义的小伙伴view
    private GetFriendLayout getFriendLayout;

    //    触摸移动
    private View moveInculde;
    //    计算便宜量
    private float touchMoveX=-1,touchMoveY=-1;
    //    记录
    private boolean isHideMove;
    protected Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_START_STREAMING:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // disable the shutter button before startStreaming
                            Log.i("mrl",isOren+"重开直播的时候");
                            if (!isOren){
                                presenter.startLive();
                            }
                            boolean res = mCameraStreamingManager.startStreaming();
                            if (!res) {
                                mHandler.sendEmptyMessage(PUBLISH_BAD);
                            }else {

                            }
                        }
                    }).start();
                    break;
                case MSG_STOP_STREAMING:
                    // disable the shutter button before stopStreaming
//                    setShutterButtonEnabled(false);
                    Log.i("mrl",isOren+"停止直播的时候"+LocalDataManager.getInstance().getLoginInfo().getToken());
                    if (!isOren) {
                        presenter.stopLive();
                    }
                    boolean res = mCameraStreamingManager.stopStreaming();
                    if (!res) {
                        toastShort("关闭播放器失败咯");
                    }
                    break;
                case PUBLISH_BAD:
                    Log.i("mrl","进来了BAD");
                    toastShort("当前状态无法直播，请重试");
                    break;
                case MSG_STOP_STREAMING_BAD:
                    toastShort("网络异常，已掉线");
                    presenter.stopLive();
                    ((RoomActivity)getActivity()).exitLiveRoom(getRoomType()!=RoomActivity.TYPE_VIEW_LIVE);
                    break;
                default:
                    break;
            }
        }
    };
    private PublishFragmentPresenter presenter;

    private CameraStreamingManager mCameraStreamingManager;
    private CameraStreamingSetting setting;
    private CameraStreamingManager.StreamingSessionListener streamingSessionListener=new CameraStreamingManager.StreamingSessionListener() {
        @Override
        public boolean onRecordAudioFailedHandled(int i) {
            mCameraStreamingManager.updateEncodingType(CameraStreamingManager.EncodingType.SW_VIDEO_CODEC);
            mCameraStreamingManager.startStreaming();
            return true;
        }

        @Override
        public boolean onRestartStreamingHandled(int i) {
            Log.i("mpush",i+"onRestartStreamingHandled");
            return mCameraStreamingManager.startStreaming();
        }

        @Override
        public Camera.Size onPreviewSizeSelected(List<Camera.Size> list) {
            return null;
        }
    };
    private CameraStreamingManager.StreamingStateListener streamingStateListener=new CameraStreamingManager.StreamingStateListener() {
        @Override
        public void onStateChanged(int i, Object o) {
            Log.i("mpush",i+"onStateChanged");
        }

        @Override
        public boolean onStateHandled(int i, Object o) {
            Log.i("mpush",i+"onStateHandled");
            return false;
        }
    };

    public static PublishFragment newInstance(@NonNull Bundle bundle) {
        PublishFragment fragment = new PublishFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public static Bundle createArgs(@NonNull String pushAddress){
        Bundle bundle = new Bundle();
        bundle.putString(ARG_PUSH_ADDRESS, pushAddress);
        return  bundle;
    }



    @Override
    protected int getLayoutId() {
        return R.layout.frag_room_publish;
    }
    //Mrl L
    public void getViewPagerJson(String user_id,String user_token) {
        Request<JSONObject> request = NoHttp.createJsonObjectRequest(Const.MAIN_HOST_URL+"/OpenAPI/V1/Anchor/getAnchorBean", RequestMethod.GET);
        request.add("token",user_token);
        request.add("user_id", user_id);

        BeautyLiveApplication.getRequestQueue().add(PAGER_JSON, request, ViewPagerOnResponse);
    }

    private OnResponseListener<JSONObject> ViewPagerOnResponse = new OnResponseListener<JSONObject>() {
        @Override
        public void onStart(int i) {
            L.i("lll", "开始了");
        }

        @Override
        public void onSucceed(int i, Response<JSONObject> response) {
            if (i == PAGER_JSON) {// 判断what是否是刚才指定的请求
                //                {"code":0,"msg":"ok","data":"320200"}这个是什么
                // 请求成功
                JSONObject result = response.get();// 响应结果
                try {
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putString("douzi",result.getString("data"));
                    msg.what=1;
                    msg.setData(data);
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // 响应头
                Headers headers = response.getHeaders();
                headers.getResponseCode();// 响应码
                response.getNetworkMillis();// 请求花费的时间
            }
        }

        @Override
        public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
            L.i("lll", "请求失败了哦" + s);
        }

        @Override
        public void onFinish(int i) {
            L.i("lll", "viewpager结束了");
            handler.sendEmptyMessage(2);
        }
    };

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==1){
                tvGold.setText(msg.getData().getString("douzi"));
            }else if (msg.what==2){
                RelativeLayout.LayoutParams layoutParams =new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                Log.i("mrl",getSurfaceViewHeight()+"  "+mDanmakuView.getHeight()+"  "+llOperationBar.getHeight()+"高度");
                layoutParams.height=getSurfaceViewHeight()-mDanmakuView.getHeight();
                layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                moveInculde.setLayoutParams(layoutParams);
                moveInculde.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction()==MotionEvent.ACTION_DOWN){
                            touchMoveX=event.getX();
                            touchMoveY=event.getY();
                            onRootClickAction();
                        }
                        if (event.getAction()==MotionEvent.ACTION_CANCEL){
                            if (touchMoveX>event.getX()+80&&isHideMove){
//                        显示
                                ObjectAnimator.ofFloat(moveLayout,"X",moveLayout.getWidth(),0).setDuration(1000).start();
                                isHideMove=false;
                            }else if (touchMoveX<event.getX()-80&&!isHideMove){
//                        隐藏
                                ObjectAnimator.ofFloat(moveLayout,"X",0,moveLayout.getWidth()).setDuration(1000).start();
                                isHideMove=true;
                            }
                        }
                        if (event.getAction()==MotionEvent.ACTION_UP){
                            if (touchMoveX>event.getX()+80&&isHideMove){
//                        显示
                                ObjectAnimator.ofFloat(moveLayout,"X",moveLayout.getWidth(),0).setDuration(1000).start();
                                isHideMove=false;
                            }else if (touchMoveX<event.getX()-80&&!isHideMove){
//                        隐藏
                                ObjectAnimator.ofFloat(moveLayout,"X",0,moveLayout.getWidth()).setDuration(1000).start();
                                isHideMove=true;
                            }
                        }
                        return true;
                    }
                });
            }
        }
    };


    @Override
    protected void initViews(View view) {
        super.initViews(view);
        L.e("lww",""+CreateRoomActivity.changed);
                if (CreateRoomActivity.changed==2) {
                    isOren = true;
//                        toastForNotImplementedFeature();
                    mHandler.removeCallbacks(mEncodingOrientationSwitcher);
                    mHandler.post(mEncodingOrientationSwitcher);
                }

        timingLogger.reset(TIMING_LOG_TAG, "PublishFragment.initViews");
        presenter = new PublishFragmentPresenter(this);
        presenter.loadFriendList();
        if (toptabstart!=null){
            toptabstart.setVisibility(View.GONE);
        }
        mRoomOwner = $(view, R.id.room_owner);
        getFriendLayout= (GetFriendLayout) friendLayout.findViewById(R.id.friend);
        RxView.clicks(mRoomOwner).throttleFirst(Const.VIEW_THROTTLE_TIME,
                TimeUnit.MILLISECONDS).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                UserInfo info = new UserInfo();
                info.setId(LocalDataManager.getInstance().getLoginInfo().getUserId());
                info.setNickname(LocalDataManager.getInstance().getLoginInfo().getNickname());
                info.setAvatar(LocalDataManager.getInstance().getLoginInfo().getAvatar());
                info.setLevel(LocalDataManager.getInstance().getLoginInfo().getLevel());
                info.setSnap(LocalDataManager.getInstance().getLoginInfo().getSnap());
                info.setCity(LocalDataManager.getInstance().getLoginInfo().getCity());
                showUserInfoDialog(info);
            }
        });

        //显示主播信息
        SimpleDraweeView draweeAnchor = $(view, R.id.img_user_avatar);
        String myAvatar = LocalDataManager.getInstance().getLoginInfo().getAvatar();
        if (!TextUtils.isEmpty(myAvatar)) {
            draweeAnchor.setImageURI(SourceFactory.wrapPathToUri(myAvatar));
        }
        tvOnlineCount.setText(String.valueOf(0));
        user_id=LocalDataManager.getInstance().getLoginInfo().getUserId();
        user_token=LocalDataManager.getInstance().getLoginInfo().getToken();
        getViewPagerJson(user_id,user_token);

//        倒计时
        tvPublishCountDown = $(view, R.id.room_live_publish_tv_countdown);
//        mSurfaceView = $(view, R.id.room_publish_surface);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams
                .MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        lp.height = getSurfaceViewHeight();
//        mSurfaceView.setLayoutParams(lp);
//        mSurfaceHolder = mSurfaceView.getHolder();
//        mSurfaceHolder.addCallback(this);
//        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        timingLogger.addSplit("init presenter, drawee & SurfaceView");

        initOperationBars(view);
        timingLogger.addSplit("initOperationBars");

//        initPreview();
        timingLogger.addSplit("initPreview");
        timingLogger.dumpToLog();
        if (mRankLay != null) {
            RxView.clicks(mRankLay)
                    .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                    .subscribe(new Action1<Void>() {
                        @Override
                        public void call(Void aVoid) {
                            showRank();
                        }
                    });
        }

        AspectFrameLayout afl = $(view, R.id.cameraPreview_afl);
        afl.setShowMode(AspectFrameLayout.SHOW_MODE.FULL);
        GLSurfaceView glSurfaceView = $(view, R.id.cameraPreview_surfaceView);
        String streamJsonStrFromServer = getArguments().getString(ARG_PUSH_ADDRESS);
        glSurfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction()==MotionEvent.ACTION_MOVE) {
                }
                return false;
            }
        });
        JSONObject streamJson = null;
        try {
            streamJson = new JSONObject(streamJsonStrFromServer);
        } catch (JSONException e) {
            e.printStackTrace();
            toastShort("创建直播流失败");
            return ;
        }

        StreamingProfile.Stream stream = new StreamingProfile.Stream(streamJson);
        StreamingProfile.AudioProfile aProfile = new StreamingProfile.AudioProfile(44100, 96 * 1024);
        StreamingProfile.VideoProfile vProfile = new StreamingProfile.VideoProfile(30, 1280 * 720, 48);
        StreamingProfile.AVProfile avProfile = new StreamingProfile.AVProfile(vProfile, aProfile);

        profile = new StreamingProfile();
        profile.setVideoQuality(StreamingProfile.VIDEO_QUALITY_HIGH1)
                .setAudioQuality(StreamingProfile.AUDIO_QUALITY_LOW2)
                .setAVProfile(avProfile)
                .setEncodingSizeLevel(StreamingProfile.VIDEO_ENCODING_HEIGHT_720)
                .setEncoderRCMode(StreamingProfile.EncoderRCModes.QUALITY_PRIORITY)
                .setEncodingOrientation(StreamingProfile.ENCODING_ORIENTATION.PORT)
//                .setDnsManager(getMyDnsManager())
                .setStreamStatusConfig(new StreamingProfile.StreamStatusConfig(3))
                .setSendingBufferProfile(new StreamingProfile.SendingBufferProfile(0.2f, 0.8f, 3.0f, 20 * 1000))
                .setStream(stream);

        setting = new CameraStreamingSetting();
        setting.setCameraId(Camera.CameraInfo.CAMERA_FACING_FRONT)
                .setFocusMode(CameraStreamingSetting.FOCUS_MODE_CONTINUOUS_VIDEO)
                .setContinuousFocusModeEnabled(true)
                .setBuiltInFaceBeautyEnabled(true)
                .setCameraPrvSizeLevel(CameraStreamingSetting.PREVIEW_SIZE_LEVEL.SMALL)
                .setCameraPrvSizeRatio(CameraStreamingSetting.PREVIEW_SIZE_RATIO.RATIO_16_9)
                .setFaceBeautySetting(new CameraStreamingSetting.FaceBeautySetting(0.7f, 0.8f, 0.8f))
                .setVideoFilter(CameraStreamingSetting.VIDEO_FILTER_TYPE.VIDEO_FILTER_BEAUTY);
        mCameraStreamingManager = new CameraStreamingManager(getActivity(), afl, glSurfaceView,
                CameraStreamingManager.EncodingType.SW_VIDEO_WITH_SW_AUDIO_CODEC);
        mCameraStreamingManager.prepare(setting, profile);
        mCameraStreamingManager.setVideoFilterType(CameraStreamingSetting.VIDEO_FILTER_TYPE.VIDEO_FILTER_BEAUTY);
        mCameraStreamingManager.setStreamingStateListener(this);
        mCameraStreamingManager.setStreamingSessionListener(streamingSessionListener);
//     注释掉 防止自己点亮
//        RxView.clicks(afl).subscribe(new Action1<Void>() {
//            @Override
//            public void call(Void aVoid) {
//                onRootClickAction();
//            }
//        });
        mCameraStreamingManager.setStreamStatusCallback(new StreamStatusCallback() {
            @Override
            public void notifyStreamStatusChanged(StreamingProfile.StreamStatus streamStatus) {
//                Log.i("mrl","videofps:"+streamStatus.videoFps+"   audioFps:"+streamStatus.audioFps+" videoBitrate:"+ streamStatus.videoBitrate);
            }
        });

        getMyPath();

        moveInculde=$(view,R.id.room_move_view);
    }

    /**
     * 展示秀币排行榜
     */
    private void showRank() {
        isCameraManagerPause=false;
        if (LocalDataManager.getInstance().getLoginInfo() != null) {
            //TODO 需要添加目前的秀币
            startActivity(CurrencyActivity.createIntent(getActivity(), LocalDataManager
                    .getInstance().getLoginInfo().getUserId(), 0 + ""));
        }
    }

    @Override
    protected int getRoomType() {
        return RoomActivity.TYPE_PUBLISH_LIVE;
    }

    @Override
    protected void parseArguments(Bundle bundle) {
        //Empty
    }

    @Override
    protected String getWsRoomId() {
        return LocalDataManager.getInstance().getLoginInfo().getCurrentRoomNum();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (countdownSubscription != null && (!countdownSubscription.isUnsubscribed())) {
            countdownSubscription.unsubscribe();
        }
        stopOrienStreaming();
        mCameraStreamingManager.destroy();
        isCameraManagerPause=true;
    }

    private void initOperationBars(@NonNull View view) {
        //相机和闪光
        final ImageButton imgbtnCamera = $(view, R.id.room_imgbtn_flash);
        RxView.clicks(imgbtnCamera)
                .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (popupWindowCamera == null) {
                            View view = LayoutInflater.from(getActivity())
                                    .inflate(R.layout.popup_room_camera, null);
//                            闪光灯
                            RxView.clicks($(view, R.id.popup_menu_flash))
                                    .subscribeOn(AndroidSchedulers.mainThread())
                                    .observeOn(Schedulers.io())
                                    .subscribe(new Action1<Void>() {
                                        @Override
                                        public void call(Void aVoid) {
                                            if (!mIsTorchOn) {
                                                mCameraStreamingManager.turnLightOn();
                                            } else {
                                                mCameraStreamingManager.turnLightOff();
                                            }
                                            mIsTorchOn = !mIsTorchOn;
                                        }
                                    });
//                            美颜
                            RxView.clicks($(view,R.id.popup_menu_beautiful))
                                    .subscribeOn(AndroidSchedulers.mainThread())
                                    .observeOn(Schedulers.io())
                                    .subscribe(new Action1<Void>() {
                                        @Override
                                        public void call(Void aVoid) {
                                            if (mBeautiful) {
                                                mCameraStreamingManager.setVideoFilterType(CameraStreamingSetting.VIDEO_FILTER_TYPE.VIDEO_FILTER_NONE);
                                            } else {
                                                mCameraStreamingManager.setVideoFilterType(CameraStreamingSetting.VIDEO_FILTER_TYPE.VIDEO_FILTER_BEAUTY);
                                            }
                                            mBeautiful = !mBeautiful;
                                        }
                                    });
                            //推流地址
                            RxView.clicks($(view,R.id.popup_menu_address))
                                    .subscribe(new Action1<Void>() {
                                        @Override
                                        public void call(Void aVoid) {
                                            showDialog();
                                        }
                                    });
//                            摄像头翻转的哦哦哦哦哦
                            RxView.clicks($(view, R.id.popup_menu_reverse_camera))
                                    .subscribe(new Action1<Void>() {
                                        @Override
                                        public void call(Void aVoid) {
                                            if (canReverseCamera) {
                                                try {
//                                                    翻转摄像头
                                                    changeCamera();
                                                } catch (IOException e) {
                                                    L.e(LOG_TAG, "Unable to reverse camera", e);
                                                }
                                            }
                                        }
                                    }, new Action1<Throwable>() {
                                        @Override
                                        public void call(Throwable throwable) {
                                            L.e(LOG_TAG, "Reverse camera error!", throwable);
                                        }
                                    });
                            popupWindowCamera = new PopupWindow(view, ViewGroup.LayoutParams
                                    .WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
                        }
                        if (!popupWindowCamera.isShowing()) {
//                            popupWindowCamera.showAsDropDown(imgbtnCamera);
                            showPopupWindowAboveButton(popupWindowCamera, imgbtnCamera);
                        }
                    }
                });
        final ImageButton imgbtnMusic = $(view, R.id.room_imgbtn_music);
        RxView.clicks(imgbtnMusic)
                .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        isOren=true;
//                        toastForNotImplementedFeature();
                        mHandler.removeCallbacks(mEncodingOrientationSwitcher);
                        mHandler.post(mEncodingOrientationSwitcher);
                    }
                });
    }

    private void changeCamera() throws IOException {
//        停止推流
        mHandler.removeCallbacks(mSwitcher);
//        100毫秒之后开启
        mHandler.postDelayed(mSwitcher, 100);
    }

    /**
     * 用于接收Activity发来的消息，终止直播。
     * 由于调用这个方法即表示不再推流，所以可以在这里直接关闭相机、闪光灯等，可以提高退出Activity的延迟。
     */
    public void prepareExit() {
        timingLogger.reset(TIMING_LOG_TAG, "PublishFragment.onDestroyView");
        Observable.just(isStart)
                .filter(new Func1<Boolean, Boolean>() {
                    @Override
                    public Boolean call(Boolean aBoolean) {
                        return isStart;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        TimingLogger logger = new TimingLogger(TIMING_LOG_TAG,
                                "SmartPublisherClose");
                        mCameraStreamingManager.pause();
                        mCameraStreamingManager.stopStreaming();
                        logger.addSplit("StopPublish");
                        logger.dumpToLog();
                    }
                });

        timingLogger.addSplit("stop native publish");
        //Camera的操作放到主线程，保证下次进入时相机不是被占用的状态
        timingLogger.addSplit("release camera");
        timingLogger.dumpToLog();
    }

    @Override
    protected boolean shouldSendHeartRequest() {
        //直播页面永远不发送
        return false;
    }

    @Override
    public void onResume() {
//        MobclickAgent.onPageStart("用户开播");
        super.onResume();
        if (!isCameraManagerPause){

        }else {
            try {
                mCameraStreamingManager.resume();
            } catch (Exception e) {
                toastShort("Device open error!");
            }
        }
        L.i(LOG_TAG, "tid:" + Thread.currentThread().getId());

    }

    @Override
    public void onPause() {
//        MobclickAgent.onPageEnd("用户开播");
        super.onPause();
//        mIsReady = false;
////        mShutterButtonPressed = false;
        if (!isCameraManagerPause){

        }else {
            mCameraStreamingManager.pause();
        }
//        mHandler.removeCallbacksAndMessages(null);
    }

    protected void startStreaming() {
        mHandler.removeCallbacksAndMessages(null);
        final Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim
                .create_room_count_down);
        if (Countdown==1) {
            Countdown++;
            countdownSubscription = Observable.interval(500, 1000, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long sequence) {
//                        调用以后这里就会进行倒计时，这里线程不是守护的 所以当我在321之内切换摄像头会有一个时差，这个时差导致了 翻转以后的倒数会有空
                            if (sequence <= 2) {
                                tvPublishCountDown.setText(String.valueOf(3 - sequence));
                                tvPublishCountDown.clearAnimation();
                                tvPublishCountDown.startAnimation(animation);
                            } else {
                                countdownSubscription.unsubscribe();
                                countdownSubscription = null;
                                tvPublishCountDown.setVisibility(View.INVISIBLE);
                                mHandler.sendEmptyMessage(MSG_START_STREAMING);
                                isStart = true;
                            }
                        }
                    });
        }
    }
//
//    protected void stopStreaming() {
//        mHandler.removeCallbacksAndMessages(null);
//        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_STOP_STREAMING), 50);
//    }

    protected void badStreaming() {
        mHandler.removeCallbacksAndMessages(null);
        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_STOP_STREAMING_BAD), 50);
    }

//    状态变化
    @Override
    public void onStateChanged(final int state, Object extra) {
        switch (state) {
            case CameraStreamingManager.STATE.PREPARING:
                break;
            case CameraStreamingManager.STATE.READY:
                mIsReady = true;
                // start streaming when READY
                startStreaming();
                break;
            case CameraStreamingManager.STATE.CONNECTING:
                break;
            case CameraStreamingManager.STATE.STREAMING:
                break;
            case CameraStreamingManager.STATE.SHUTDOWN:
                if (mOrientationChanged) {
                    mOrientationChanged = false;
                    startOrienStreaming();
                }
                break;
            case CameraStreamingManager.STATE.IOERROR:
                Log.i("mpush",extra+"网络异常掉线");
                badStreaming();
                break;
            case CameraStreamingManager.STATE.UNKNOWN:
                break;
            case CameraStreamingManager.STATE.SENDING_BUFFER_EMPTY:
                break;
            case CameraStreamingManager.STATE.SENDING_BUFFER_FULL:
                break;
            case CameraStreamingManager.STATE.AUDIO_RECORDING_FAIL:
                break;
            case CameraStreamingManager.STATE.OPEN_CAMERA_FAIL:
                L.e(LOG_TAG, "Open Camera Fail. id:" + extra);
                break;
            case CameraStreamingManager.STATE.DISCONNECTED:
                Log.i("mpush",extra+"网络异常正在重连");
                break;
            case CameraStreamingManager.STATE.INVALID_STREAMING_URL:
                L.e(LOG_TAG, "Invalid streaming url:" + extra);
                break;
            case CameraStreamingManager.STATE.CAMERA_SWITCHED:
                if (extra != null) {
                    L.i(LOG_TAG, "current camera id:" + extra);
                }
                L.i(LOG_TAG, "camera switched");
                break;
            case CameraStreamingManager.STATE.TORCH_INFO:
                if (extra != null) {
                    final boolean isSupportedTorch = (Boolean) extra;
                    L.i(LOG_TAG, "isSupportedTorch=" + isSupportedTorch);
                }
                break;
        }
    }

    @Override
    public boolean onStateHandled(final int state, Object extra) {
        switch (state) {
            case CameraStreamingManager.STATE.SENDING_BUFFER_HAS_FEW_ITEMS:
                return false;
            case CameraStreamingManager.STATE.SENDING_BUFFER_HAS_MANY_ITEMS:
                return false;
        }
        return false;
    }

    @Override
    public void showFriendList(List<GetFriendBean> friendBeanList) {
        getFriendLayout.setFriendList(friendBeanList);
    }

    private class Switcher implements Runnable {
        @Override
        public void run() {
            mCameraStreamingManager.switchCamera();
        }
    }

//      切换横竖屏的类哦
    private class EncodingOrientationSwitcher implements Runnable {
        @Override
        public void run() {
            stopOrienStreaming();
            mOrientationChanged = !mOrientationChanged;
            isEncOrientationPort = !isEncOrientationPort;
            profile.setEncodingOrientation(isEncOrientationPort ? StreamingProfile.ENCODING_ORIENTATION.PORT : StreamingProfile.ENCODING_ORIENTATION.LAND);
            mCameraStreamingManager.setStreamingProfile(profile);
            getActivity().setRequestedOrientation(isEncOrientationPort ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            mCameraStreamingManager.notifyActivityOrientationChanged();
            updateOrientationBtnText();
        }
    }

//    切换图片
    private void updateOrientationBtnText() {
        if (isEncOrientationPort) {
        } else {
        }
    }
    protected void stopOrienStreaming() {
        mHandler.removeCallbacksAndMessages(null);
        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_STOP_STREAMING), 50);
    }

    protected void startOrienStreaming() {
        mHandler.removeCallbacksAndMessages(null);
        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_START_STREAMING), 50);
    }
    private void showDialog() {
        final BaseActivity activity = (BaseActivity) getActivity();
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("是否复制我的直播地址");
        builder.setMessage(myPlayPath);
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager)getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                clipboardManager.setText(myPlayPath);
                toastShort("复制成功");
            }
        });
        builder.show();
    }
    int MES=8;
    public void getMyPath(){
//      域名 139.129.19.190
        Request<JSONObject> request = NoHttp.createJsonObjectRequest(Const.WEB_BASE_URL+"qiniu/getPullAddress", RequestMethod.GET);
        request.add("token",LocalDataManager.getInstance().getLoginInfo().getToken());
        request.add("roomID",LocalDataManager.getInstance().getLoginInfo().getCurrentRoomNum());
        BeautyLiveApplication.getRequestQueue().add(MES, request, upMyPathResponse);
    }

    private OnResponseListener<JSONObject> upMyPathResponse = new OnResponseListener<JSONObject>() {
        @Override
        public void onStart(int i) {
            L.i("lll", "开始了");
        }

        @Override
        public void onSucceed(int i, Response<JSONObject> response) {
            if (i == MES) {// 判断what是否是刚才指定的请求
                //                {"code":0,"msg":"ok","data":"320200"}这个是什么
                // 请求成功
                JSONObject result = response.get();// 响应结果
                try {
                    myPlayPath=result.getString("data");
                    Log.i("mrl",result.toString()+" "+result.getString("data"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // 响应头
                Headers headers = response.getHeaders();
                headers.getResponseCode();// 响应码
                response.getNetworkMillis();// 请求花费的时间
            }
        }

        @Override
        public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
            L.i("lll", "请求失败了哦" + s);
        }

        @Override
        public void onFinish(int i) {
            L.i("lll", "viewpager结束了");
        }
    };
}
